import {defineStore} from "pinia";
import {getAdminInfo, getSysAdminList, getSysOutLogin, postLogin} from "@/api/admin";
import type {ILoginResponseData, TAdminInfo, TLoginForm, TRoute} from "@/api/admin/type.ts";
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from "@/utils";
import {ElMessage} from "element-plus";
import {setRoute} from "@/router";
import useSettingStore from "@/store/modules/setting.ts";
const settingStore =  useSettingStore();

type TState = {
    token:string | null,
    info:TAdminInfo | null,
    routeList:TRoute[],
    adminList:TAdminInfo[],
    keyword:string
}

const useAdmin = defineStore("Admin",{
    state():TState{
        return {
            token:GET_TOKEN(),
            info:null,
            routeList:[],
            adminList:[],
            keyword:""
        }
    },
    actions:{
        // 登陆功能
        async postLoginAsync(loginForm:TLoginForm){
            // 调用登陆的接口
            const result:ILoginResponseData =  await postLogin(loginForm);
            // 设置localStorage
            SET_TOKEN(result.token);
            // 设置当前小仓库的数据状态token
            this.token = result.token;
            // 获取个人信息
            await this.getAdminInfoAsync();
        },
        // 获取管理员信息
        async getAdminInfoAsync(){
            try{
                const result = await getAdminInfo();
                this.info = result.info;
                this.routeList = result.routeList;
                setRoute(result.routeList,"index");
            }catch (err){

            }
        },
        // 退出登陆
        async getSysOutLoginAsync(){
            const {message} = await getSysOutLogin();
            ElMessage.success(message);
            REMOVE_TOKEN();
        },
        // 获取管理员列表
        async getSysAdminListAsync(pageNo:number=1){
            const result = await getSysAdminList(pageNo,settingStore.pageInfo.pageSize,this.keyword);
            this.adminList = result.adminList;
            settingStore.pageInfo = {
                pageNo:result.pageNo,
                pageSize:result.pageSize,
                total:result.total
            }

        }
    }
});
export default useAdmin;